package com.fouram.web.filter;

import com.fouram.core.constants.GlobalConstants;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * mdc过滤器
 * @author liupeng
 */
public class MDCFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestId = httpRequest.getHeader(GlobalConstants.TRACE_ID);
        if (requestId == null) {
            requestId = UUID.randomUUID().toString();
        }
        MDC.put(GlobalConstants.TRACE_ID, requestId);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(GlobalConstants.TRACE_ID);
        }
    }
}